import { ref } from 'vue'
import { ctpService } from '../services/ctpService'
import { contractService } from '../services/contractService'
import TimeService from '../services/timeService'

// 根据CTP期货交易价格规则生成默认priceTick
const generateDefaultPriceTick = (contractCode) => {
  if (!contractCode) return 1;
  
  const upperCode = contractCode.toUpperCase();
  
  // 根据合约品种设置默认价格间距
  if (upperCode.startsWith('RB') || upperCode.startsWith('HC') || upperCode.startsWith('SS')) {
    // 螺纹钢、热卷、不锈钢：1元
    return 1;
  } else if (upperCode.startsWith('I') || upperCode.startsWith('J') || upperCode.startsWith('JM')) {
    // 铁矿石、焦炭、焦煤：0.5元
    return 0.5;
  } else if (upperCode.startsWith('AG') || upperCode.startsWith('AU')) {
    // 白银、黄金：0.02元
    return 0.02;
  } else if (upperCode.startsWith('CU') || upperCode.startsWith('AL') || upperCode.startsWith('ZN')) {
    // 铜、铝、锌：5元
    return 5;
  } else if (upperCode.startsWith('C') || upperCode.startsWith('CS') || upperCode.startsWith('A')) {
    // 玉米、玉米淀粉、豆一：1元
    return 1;
  } else if (upperCode.startsWith('M') || upperCode.startsWith('Y') || upperCode.startsWith('P')) {
    // 豆粕、豆油、棕榈油：1元
    return 1;
  } else if (upperCode.startsWith('AP')) {
    // 苹果：1元
    return 1;
  } else if (upperCode.startsWith('CF') || upperCode.startsWith('SR')) {
    // 棉花、白糖：5元
    return 5;
  } else if (upperCode.startsWith('TA') || upperCode.startsWith('MA')) {
    // PTA、甲醇：1元
    return 1;
  } else if (upperCode.startsWith('FG') || upperCode.startsWith('SA')) {
    // 玻璃、纯碱：1元
    return 1;
  } else {
    // 默认价格间距：1元
    return 1;
  }
};

export function useMarketData(contractCode, priceTick) {
  // 为每个面板实例创建独立的标识符
  const panelInstanceId = `panel_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`
  
  // 确定最终使用的价格间距
  const finalPriceTick = priceTick || generateDefaultPriceTick(contractCode)

  // 市场数据状态
  const isUsingRealData = ref(false)
  const currentPrice = ref(0)
  const priceDirection = ref('neutral')
  const priceChangePercent = ref('')
  const totalVolume = ref(0)
  const totalPosition = ref(0)
  const dailyPositionChange = ref(0)
  const redValue = ref(0)
  const blueValue = ref(0)

  // 涨跌停价格
  const upperLimitPrice = ref(0)  // 涨停价
  const lowerLimitPrice = ref(0)  // 跌停价

  // 特殊价格
  const openPrice = ref(0)        // 开盘价
  const highestPrice = ref(0)     // 最高价
  const lowestPrice = ref(0)      // 最低价
  const bid1Price = ref(0)        // 买一价
  const ask1Price = ref(0)        // 卖一价

  // 价格档位数据
  const sellOrders = ref([])
  const buyOrders = ref([])
  const marketDataMap = ref(new Map())
  const processedOrderBook = ref({
    sell: [],
    buy: []
  })

  // 价格档位配置
  const PRICE_LEVELS = ref({
    SELL_LEVELS: 0,
    BUY_LEVELS: 0,
    PRICE_STEP: finalPriceTick
  })

  // 每个面板实例的独立订阅管理
  const currentSubscribedContract = ref('')  // 当前面板订阅的合约
  let marketDataListener = null  // 当前面板的独立监听器
  let isUpdatingOrders = false

  // 行情数据时间戳
  const lastUpdateTime = ref('')
  const lastUpdateTimestamp = ref(0)

  // 动态计算表格行数
  const calculateTableRows = (tableContainer) => {
    if (!tableContainer) return

    const containerHeight = tableContainer.clientHeight
    const separatorHeight = 0
    const rowHeight = 18
    const availableHeight = containerHeight - separatorHeight
    const totalRows = Math.ceil(availableHeight / rowHeight)
    const sellLevels = Math.floor(totalRows / 2)
    const buyLevels = Math.floor(totalRows / 2)
    const remainingRows = totalRows - sellLevels - buyLevels
    const finalSellLevels = sellLevels + remainingRows
    const finalBuyLevels = buyLevels

    PRICE_LEVELS.value.SELL_LEVELS = Math.max(finalSellLevels, 1)
    PRICE_LEVELS.value.BUY_LEVELS = Math.max(finalBuyLevels, 1)

  }

  // 价格连续性检查
  const validatePriceContinuity = (prices, context = '') => {
    if (prices.length < 2) return true

    let isValid = true
    const issues = []

    for (let i = 1; i < prices.length; i++) {
      const priceDiff = Math.abs(prices[i - 1] - prices[i])
      const expectedDiff = PRICE_LEVELS.value.PRICE_STEP

      if (Math.abs(priceDiff - expectedDiff) > 0.001) {
        isValid = false
        issues.push(`位置${i}: ${prices[i - 1]} -> ${prices[i]} (差值: ${priceDiff}, 期望: ${expectedDiff})`)
      }
    }
    return isValid
  }

  // 填补价格缺口
  const fillPriceGaps = (prices) => {
    if (prices.length < 2) return prices

    const sortedPrices = [...prices].sort((a, b) => b - a)
    const filledPrices = []

    for (let i = 0; i < sortedPrices.length - 1; i++) {
      filledPrices.push(sortedPrices[i])

      const currentPrice = sortedPrices[i]
      const nextPrice = sortedPrices[i + 1]
      const gap = currentPrice - nextPrice
      const expectedGap = PRICE_LEVELS.value.PRICE_STEP

      if (gap > expectedGap + 0.001) {
        const missingSteps = Math.round(gap / expectedGap) - 1
        for (let step = 1; step <= missingSteps; step++) {
          const missingPrice = currentPrice - step * expectedGap
          filledPrices.push(missingPrice)
        }
      }
    }

    filledPrices.push(sortedPrices[sortedPrices.length - 1])
    return filledPrices.sort((a, b) => b - a)
  }

  // 颜色枚举
  const PriceColor = {
    RED: '#cf3e20ff',
    BLUE: '#289472ff',
    GRAY: 'gray',
    YELLOW: '#e5e047ff',      // 最高价  // 空单成交后 #aba84bff
    GREEN: '#314ce4ff',        // 最低价   // 多单成交后：#d07777ff
    LIGHT_GRAY: '#3c4a46ff' // 开盘价    // 最右侧的颜色 ：
  }

  // 获取价格背景颜色（包括特殊价格）
  const getPriceBackgroundColor = (price, bidPrice1, askPrice1) => {
    const roundedPrice = Math.round(price)
    const roundedBidPrice1 = Math.round(bidPrice1 || 0)
    const roundedAskPrice1 = Math.round(askPrice1 || 0)

    // 检查特殊价格
    if (highestPrice.value > 0 && roundedPrice === highestPrice.value) {
      return PriceColor.YELLOW  // 最高价：黄色
    }
    if (lowestPrice.value > 0 && roundedPrice === lowestPrice.value) {
      return PriceColor.GREEN   // 最低价：绿色
    }
    if (openPrice.value > 0 && roundedPrice === openPrice.value) {
      return PriceColor.LIGHT_GRAY  // 开盘价：浅灰色
    }

    // 常规价格颜色规则
    if (roundedAskPrice1 > 0 && roundedPrice >= roundedAskPrice1) {
      return PriceColor.RED     // 卖一价及以上：红色
    }
    if (roundedBidPrice1 > 0 && roundedPrice <= roundedBidPrice1) {
      return PriceColor.BLUE    // 买一价及以下：蓝色
    }

    return PriceColor.GRAY      // 买一价和卖一价之间：灰色
  }

  // 获取价格颜色
  const getPriceColor = (lastPrice, bidPrice, askPrice, prevLastPrice = null) => {
    if (lastPrice >= askPrice) return PriceColor.BLUE
    if (lastPrice <= bidPrice) return PriceColor.RED

    if (bidPrice < lastPrice && lastPrice < askPrice) {
      if (prevLastPrice !== null) {
        if (lastPrice > prevLastPrice) return PriceColor.BLUE
        if (lastPrice < prevLastPrice) return PriceColor.RED
      }
      return PriceColor.GRAY
    }

    return PriceColor.GRAY
  }

  // 渲染订单簿
  const renderOrderBook = (bids, asks, lastPrice, prevLastPrice = null) => {
    const result = []
    const allPrices = new Set()

    bids.forEach(([price, volume]) => {
      if (price > 0) allPrices.add(price)
    })

    asks.forEach(([price, volume]) => {
      if (price > 0) allPrices.add(price)
    })

    if (lastPrice > 0) allPrices.add(lastPrice)

    const sortedPrices = Array.from(allPrices).sort((a, b) => b - a)

    const bidMap = new Map()
    const askMap = new Map()

    bids.forEach(([price, volume]) => {
      bidMap.set(price, volume)
    })

    asks.forEach(([price, volume]) => {
      askMap.set(price, volume)
    })

    sortedPrices.forEach(price => {
      const bidVolume = bidMap.get(price) || 0
      const askVolume = askMap.get(price) || 0

      let color = PriceColor.GRAY

      if (price === lastPrice) {
        color = PriceColor.GRAY
      } else if (price > lastPrice) {
        color = PriceColor.RED
        if (askVolume > 0 && price <= lastPrice) {
          color = PriceColor.BLUE
        }
      } else {
        color = PriceColor.BLUE
        if (bidVolume > 0 && price >= lastPrice) {
          color = PriceColor.RED
        }
      }

      if (prevLastPrice !== null && price === lastPrice) {
        color = lastPrice > prevLastPrice ? PriceColor.BLUE :
          lastPrice < prevLastPrice ? PriceColor.RED : PriceColor.GRAY
      }

      result.push({
        price,
        buyVolume: bidVolume,
        sellVolume: askVolume,
        color,
        level: '1'
      })
    })
    return result
  }

  // 生成空的价格档位
  const generateEmptyPriceOrders = () => {
    const emptySellOrders = []
    for (let i = 1; i <= PRICE_LEVELS.value.SELL_LEVELS; i++) {
      emptySellOrders.push({
        price: 0,
        buyVolume: 0,
        sellVolume: 0,
        level: i.toString()
      })
    }
    emptySellOrders.reverse()

    const emptyBuyOrders = []
    for (let i = 1; i <= PRICE_LEVELS.value.BUY_LEVELS; i++) {
      emptyBuyOrders.push({
        price: 0,
        buyVolume: 0,
        sellVolume: 0,
        level: i.toString()
      })
    }

    sellOrders.value = emptySellOrders
    buyOrders.value = emptyBuyOrders
  }

  // 更新当前价格（增强版，支持价格波动跟踪）
  const updateCurrentPrice = (newPrice) => {
    const oldPrice = currentPrice.value
    const newPriceRounded = Math.round(newPrice)

    if (newPriceRounded > oldPrice) {
      priceDirection.value = 'up'
    } else if (newPriceRounded < oldPrice) {
      priceDirection.value = 'down'
    } else {
      priceDirection.value = 'neutral'
    }

    currentPrice.value = newPriceRounded

    // 价格波动处理：如果价格变化较大，可能需要重新调整显示范围
    handlePriceFluctuation(newPriceRounded, oldPrice)

    setTimeout(() => {
      priceDirection.value = 'neutral'
    }, 3000)
  }

  // 价格波动处理逻辑
  const handlePriceFluctuation = (newPrice, oldPrice) => {
    // 只有在价格确实发生变化时才处理
    if (newPrice === oldPrice) return

    // 这里可以添加更多的价格波动处理逻辑
    // 例如：动态调整显示范围、平滑滚动等
    // 当前保持简单实现，主要功能在generatePriceOrders中的动态分割线已经实现
  }

  // 动态分割线定位策略
  const getDynamicSeparatorPosition = (bidPrice1, askPrice1, allPrices) => {
    // 策略1: 基于买一价/卖一价的实际位置
    const askIndex = allPrices.findIndex(p => p === Math.round(askPrice1))
    const bidIndex = allPrices.findIndex(p => p === Math.round(bidPrice1))
    
    if (askIndex !== -1 && bidIndex !== -1) {
      // 分割线放在买一价和卖一价之间
      const separatorPos = Math.floor((askIndex + bidIndex) / 2)
      return separatorPos
    }
    
    // 策略2: 基于价格中位数
    const midPrice = (bidPrice1 + askPrice1) / 2
    const midIndex = allPrices.findIndex(p => p <= midPrice)
    
    return midIndex !== -1 ? midIndex : Math.floor(allPrices.length / 2)
  }

  // 清理当前面板的订阅
  const cleanupCurrentSubscription = async () => {
    if (currentSubscribedContract.value) {

      try {
        // 取消订阅当前合约（传递面板ID，支持多面板共享）
        const unsubscribeSuccess = await contractService.unsubscribeContractMarketData(currentSubscribedContract.value, panelInstanceId)
        if (unsubscribeSuccess) {
        } else {
        }
      } catch (error) {
      }

      // 移除当前面板的事件监听器
      if (marketDataListener) {
        ctpService.off('market_data', marketDataListener)
        marketDataListener = null
      }

      // 清空当前面板的订阅
      currentSubscribedContract.value = ''
    }
  }

  // 更新行情数据（只处理当前面板订阅的合约）
  const updateMarketData = (data) => {
    // 验证数据是否属于当前面板订阅的合约
    if (!data.instrument_id || data.instrument_id !== currentSubscribedContract.value) {
      return
    }


    // 处理CTP时间戳
    if (data.update_time && data.update_millisec !== undefined) {
      try {
        const ctpTime = TimeService.formatCTPTime(data.update_time, data.update_millisec, {
          showMilliseconds: true,
          use24Hour: true,
          showDate: false
        })
        lastUpdateTime.value = ctpTime
        lastUpdateTimestamp.value = TimeService.parseCTPTime(data.update_time, data.update_millisec).getTime()
      } catch (error) {
      }
    }

    // 更新基础行情信息
    if (data.last_price && data.last_price > 0) {
      updateCurrentPrice(data.last_price)
    }

    // 更新价格变化百分比
    if (data.pre_settlement_price && data.pre_settlement_price > 0 && data.last_price && data.last_price > 0) {
      const changePercent = ((data.last_price - data.pre_settlement_price) / data.pre_settlement_price * 100).toFixed(2)
      priceChangePercent.value = changePercent
    }

    // 更新涨跌停价格
    if (data.upper_limit_price && data.upper_limit_price > 0) {
      upperLimitPrice.value = data.upper_limit_price
    }
    if (data.lower_limit_price && data.lower_limit_price > 0) {
      lowerLimitPrice.value = data.lower_limit_price
    }

    // 更新特殊价格
    if (data.open_price && data.open_price > 0) {
      openPrice.value = data.open_price
    }
    if (data.highest_price && data.highest_price > 0) {
      highestPrice.value = data.highest_price
    }
    if (data.lowest_price && data.lowest_price > 0) {
      lowestPrice.value = data.lowest_price
    }

    // 更新成交量和持仓量
    if (data.volume !== undefined) totalVolume.value = data.volume
    if (data.open_interest !== undefined) totalPosition.value = data.open_interest

    // 更新买一价和卖一价
    if (data.bid_price1 && data.bid_price1 > 0) {
      bid1Price.value = Math.round(data.bid_price1)
    }
    if (data.ask_price1 && data.ask_price1 > 0) {
      ask1Price.value = Math.round(data.ask_price1)
    }

    // 更新买卖盘数据到marketDataMap（处理5档行情数据）
    const price = Math.round(data.last_price || 0)
    if (price > 0) {
      // 更新5档买盘数据
      for (let i = 1; i <= 5; i++) {
        const bidPriceKey = `bid_price${i}`
        const bidVolumeKey = `bid_volume${i}`

        if (data[bidPriceKey] && data[bidPriceKey] > 0) {
          const bidPrice = Math.round(data[bidPriceKey])
          const existingData = marketDataMap.value.get(bidPrice) || { bidVolume: 0, askVolume: 0 }
          marketDataMap.value.set(bidPrice, {
            bidVolume: data[bidVolumeKey] || 0,
            askVolume: existingData.askVolume
          })
        }
      }

      // 更新5档卖盘数据
      for (let i = 1; i <= 5; i++) {
        const askPriceKey = `ask_price${i}`
        const askVolumeKey = `ask_volume${i}`

        if (data[askPriceKey] && data[askPriceKey] > 0) {
          const askPrice = Math.round(data[askPriceKey])
          const existingData = marketDataMap.value.get(askPrice) || { bidVolume: 0, askVolume: 0 }
          marketDataMap.value.set(askPrice, {
            bidVolume: existingData.bidVolume,
            askVolume: data[askVolumeKey] || 0
          })
        }
      }

      // 生成价格档位数据
      generatePriceOrders(data, data.bid_price1, data.ask_price1)
    }

  }

  // 查询行情数据
  const queryMarketData = async (contractCode) => {
    try {

      // 先清理现有订阅
      await cleanupCurrentSubscription()

      // 使用新的单个合约订阅方法，传递面板ID
      const subscribeSuccess = await contractService.subscribeContractMarketData(contractCode, panelInstanceId)

      if (subscribeSuccess) {

        // 设置当前面板订阅的合约
        currentSubscribedContract.value = contractCode

        // 创建当前面板的独立行情数据监听器
        marketDataListener = (data) => {
          // 只处理当前面板订阅的合约数据
          if (data.instrument_id === contractCode) {
            updateMarketData(data)
          }
        }

        // 监听行情数据更新
        ctpService.on('market_data', marketDataListener)

        return true
      } else {
        return false
      }
    } catch (error) {
      return false
    }
  }

  // 优化的价格档位生成方法（解决价格重复、提高性能、动态分割线定位）
  const generatePriceOrders = (data, bidPrice1, askPrice1) => {
    if (isUpdatingOrders) {
      return
    }

    isUpdatingOrders = true

    try {
      const priceStep = PRICE_LEVELS.value.PRICE_STEP
      
      if (!bidPrice1 || !askPrice1 || bidPrice1 <= 0 || askPrice1 <= 0) {
        return
      }

      const roundedBidPrice1 = Math.round(bidPrice1)
      const roundedAskPrice1 = Math.round(askPrice1)

      // 1. 计算价格范围
      const maxPrice = upperLimitPrice.value > 0 ? upperLimitPrice.value : roundedAskPrice1 + 50 * priceStep
      const minPrice = lowerLimitPrice.value > 0 ? lowerLimitPrice.value : roundedBidPrice1 - 50 * priceStep

      // 2. 生成连续价格序列（一次性生成，使用Set自动去重）
      const allPrices = new Set()
      
      // 从最高价到最低价，按价格间距生成完整序列
      for (let price = maxPrice; price >= minPrice; price -= priceStep) {
        // 确保价格精度正确，避免浮点数误差
        const roundedPrice = Math.round(price / priceStep) * priceStep
        allPrices.add(roundedPrice)
      }
      
      // 确保买一价和卖一价在序列中
      allPrices.add(roundedBidPrice1)
      allPrices.add(roundedAskPrice1)

      // 转换为排序数组
      const sortedPrices = Array.from(allPrices).sort((a, b) => b - a)

      // 3. 动态确定分割线位置（基于实际买一价/卖一价，并均分中间价格）
      let askIndex = -1
      let bidIndex = -1
      
      // 找到买一价和卖一价在价格序列中的位置
      for (let i = 0; i < sortedPrices.length; i++) {
        if (sortedPrices[i] === roundedAskPrice1) {
          askIndex = i
        }
        if (sortedPrices[i] === roundedBidPrice1) {
          bidIndex = i
        }
      }

      let separatorIndex = -1
      
      if (askIndex !== -1 && bidIndex !== -1) {
        // 计算买一价和卖一价之间的价格数量（不包括买一价和卖一价本身）
        const gapPrices = bidIndex - askIndex - 1
        
        if (gapPrices > 0) {
          // 有中间价格需要分配
          if (gapPrices % 2 === 1) {
            // 奇数个中间价格：买盘多分配一个
            const sellGapCount = Math.floor(gapPrices / 2)
            separatorIndex = askIndex + 1 + sellGapCount
          } else {
            // 偶数个中间价格：平均分配
            const sellGapCount = gapPrices / 2
            separatorIndex = askIndex + 1 + sellGapCount
          }
        } else {
          // 没有中间价格，分割线在卖一价之后
          separatorIndex = askIndex + 1
        }
        
      } else if (askIndex !== -1) {
        // 只找到卖一价
        separatorIndex = askIndex + 1
      } else if (bidIndex !== -1) {
        // 只找到买一价
        separatorIndex = bidIndex
      } else {
        // 都没找到，使用中点
        separatorIndex = Math.floor(sortedPrices.length / 2)
      }

      // 4. 分离卖盘和买盘价格
      const sellPrices = separatorIndex > 0 ? sortedPrices.slice(0, separatorIndex) : []
      const buyPrices = separatorIndex >= 0 ? sortedPrices.slice(separatorIndex) : sortedPrices

      // 5. 生成卖盘数据结构（空单区域）
      const newSellOrders = sellPrices.map((price, index) => {
        const marketData = marketDataMap.value.get(price)
        const roundedPrice = Math.round(price)
        const roundedBidPrice1 = Math.round(bidPrice1 || 0)
        const roundedAskPrice1 = Math.round(askPrice1 || 0)
        
        // 检查是否为灰色区域（买一价和卖一价之间）
        const isGrayArea = roundedBidPrice1 > 0 && roundedAskPrice1 > 0 && 
                          roundedPrice > roundedBidPrice1 && roundedPrice < roundedAskPrice1
        
        // 关键修复：空单区域只应该有卖量数据，强制清除买量数据
        // 防止lastPrice变化导致的数据残留问题
        let sellVolume = marketData?.askVolume || 0
        
        // 灰色区域不应该显示任何买卖量数据
        if (isGrayArea) {
          sellVolume = 0
        }
        
        // 如果该价格在空单区域但仍有买量数据，清除marketDataMap中的买量
        if (marketData && marketData.bidVolume > 0) {
          marketDataMap.value.set(price, {
            bidVolume: 0, // 清除买量
            askVolume: isGrayArea ? 0 : marketData.askVolume // 灰色区域也清除卖量
          })
        }
        
        return {
          price,
          buyVolume: 0, // 卖盘区域强制不显示买量
          sellVolume: sellVolume,
          level: (index + 1).toString(),
          color: getPriceBackgroundColor(price, bidPrice1, askPrice1),
          section: 'sell',
          // 额外信息：分别记录市场数据和我的数据
          marketBuyVolume: 0, // 强制为0
          marketSellVolume: sellVolume,
          myBuyVolume: 0,
          mySellVolume: 0
        }
      })

      // 6. 生成买盘数据结构（多单区域）
      const newBuyOrders = buyPrices.map((price, index) => {
        const marketData = marketDataMap.value.get(price)
        const roundedPrice = Math.round(price)
        const roundedBidPrice1 = Math.round(bidPrice1 || 0)
        const roundedAskPrice1 = Math.round(askPrice1 || 0)
        
        // 检查是否为灰色区域（买一价和卖一价之间）
        const isGrayArea = roundedBidPrice1 > 0 && roundedAskPrice1 > 0 && 
                          roundedPrice > roundedBidPrice1 && roundedPrice < roundedAskPrice1
        
        // 关键修复：多单区域只应该有买量数据，强制清除卖量数据
        // 防止lastPrice变化导致的数据残留问题
        let buyVolume = marketData?.bidVolume || 0
        
        // 灰色区域不应该显示任何买卖量数据
        if (isGrayArea) {
          buyVolume = 0
        }
        
        // 如果该价格在多单区域但仍有卖量数据，清除marketDataMap中的卖量
        if (marketData && marketData.askVolume > 0) {
          marketDataMap.value.set(price, {
            bidVolume: isGrayArea ? 0 : marketData.bidVolume, // 灰色区域也清除买量
            askVolume: 0 // 清除卖量
          })
        }
        
        return {
          price,
          buyVolume: buyVolume,
          sellVolume: 0, // 买盘区域强制不显示卖量
          level: (index + 1).toString(),
          color: getPriceBackgroundColor(price, bidPrice1, askPrice1),
          section: 'buy',
          // 额外信息：分别记录市场数据和我的数据
          marketBuyVolume: buyVolume,
          marketSellVolume: 0, // 强制为0
          myBuyVolume: 0,
          mySellVolume: 0
        }
      })

      // 7. 更新PRICE_LEVELS配置
      PRICE_LEVELS.value.SELL_LEVELS = newSellOrders.length
      PRICE_LEVELS.value.BUY_LEVELS = newBuyOrders.length

      // 8. 生成合并后的完整数据（包含section标识，按价格排序）
      const mergedOrderBook = [
        ...newSellOrders.map((item, index) => ({
          ...item,
          section: 'sell',
          rowType: 'sell-row',
          originalIndex: index
        })),
        ...newBuyOrders.map((item, index) => ({
          ...item,
          section: 'buy',
          rowType: 'buy-row',
          originalIndex: index
        }))
      ].sort((a, b) => b.price - a.price) // 按价格从高到低排序

      // 9. 更新处理后的订单簿数据（用于表格渲染）
      processedOrderBook.value = {
        sell: newSellOrders,
        buy: newBuyOrders,
        merged: mergedOrderBook  // 新增：合并后的完整数据
      }

      // 10. 更新原始数据
      sellOrders.value = newSellOrders
      buyOrders.value = newBuyOrders

    } finally {
      isUpdatingOrders = false
    }
  }

  return {
    // 状态
    isUsingRealData,
    currentPrice,
    priceDirection,
    priceChangePercent,
    totalVolume,
    totalPosition,
    dailyPositionChange,
    redValue,
    blueValue,
    upperLimitPrice,
    lowerLimitPrice,
    openPrice,
    highestPrice,
    lowestPrice,
    bid1Price,
    ask1Price,
    sellOrders,
    buyOrders,
    marketDataMap,
    processedOrderBook,
    PRICE_LEVELS,
    currentSubscribedContract,
    panelInstanceId,
    lastUpdateTime,
    lastUpdateTimestamp,

    // 方法
    calculateTableRows,
    validatePriceContinuity,
    fillPriceGaps,
    getPriceColor,
    getPriceBackgroundColor,
    renderOrderBook,
    generateEmptyPriceOrders,
    updateCurrentPrice,
    handlePriceFluctuation,
    getDynamicSeparatorPosition,
    cleanupCurrentSubscription,
    updateMarketData,
    queryMarketData,
    generatePriceOrders,

    // 常量
    PriceColor
  }
}
